
// функция для кэширования асинхронной операции
type Callback<T> = () => Promise<T>;

type MemoizedFunction<T> = () => Promise<T>;

type MemoizeFunction = <T>(cb: Callback<T>, ms: number) => MemoizedFunction<T>;

const memoize: MemoizeFunction = <T>(cb: Callback<T>, ms: number) => {
  let prevRes: T | null = null;
  let start: number | null = null;
  
  return async () => {
    if (Date.now() - (start ?? 0) >= ms) {
      prevRes = null;
      start = null;
    }
    
    if (prevRes) return prevRes;
    
    const res = await cb();
    prevRes = res;
    
    if (!start) start = Date.now();
    
    return res;
  };
};

const getData: Callback<number> = async () => {
  const randomNumber = Math.random() * 10;
  return Promise.resolve(Math.round(randomNumber));
};


 const getJsonMemoize = memoize(getData, 1000);


